import { createApp, h } from 'vue'
import ToastManager from '../components/ToastManager.vue'

interface ToastOptions {
  title: string
  message?: string
  type?: 'success' | 'error' | 'warning' | 'info'
  duration?: number
  closable?: boolean
}

class ToastService {
  private app: any = null
  private toastManager: any = null

  constructor() {
    this.init()
  }

  private init() {
    // 创建Toast管理器实例
    const container = document.createElement('div')
    container.id = 'toast-container'
    document.body.appendChild(container)

    this.app = createApp({
      render() {
        return h(ToastManager, {
          ref: 'toastManager'
        })
      },
      mounted() {
        this.toastManager = this.$refs.toastManager
      }
    })

    this.app.mount(container)
  }

  private getToastManager() {
    if (!this.app) {
      this.init()
    }
    return this.app._instance?.refs?.toastManager
  }

  show(options: ToastOptions) {
    const manager = this.getToastManager()
    if (manager) {
      manager.addToast(options)
    }
  }

  success(title: string, message?: string, duration?: number) {
    this.show({
      title,
      message,
      type: 'success',
      duration: duration || 3000
    })
  }

  error(title: string, message?: string, duration?: number) {
    this.show({
      title,
      message,
      type: 'error',
      duration: duration || 5000
    })
  }

  warning(title: string, message?: string, duration?: number) {
    this.show({
      title,
      message,
      type: 'warning',
      duration: duration || 4000
    })
  }

  info(title: string, message?: string, duration?: number) {
    this.show({
      title,
      message,
      type: 'info',
      duration: duration || 3000
    })
  }
}

// 创建全局Toast实例
const toast = new ToastService()

export default toast 